import time
import schedule
from pynput import mouse, keyboard
from dingtalkchatbot.chatbot import DingtalkChatbot, ActionCard, CardItem
import json
import sys
import os
import hashlib

#-----------------------------------------------------------------------------
# 全局变量，用于统计键盘和鼠标点击次数
keyboard_clicks = 0
mouse_clicks = 0

# 键盘事件处理函数
def on_key_press(key):
    global keyboard_clicks
    keyboard_clicks += 1

# 鼠标事件处理函数
def on_mouse_click(x, y, button, pressed):
    global mouse_clicks
    if pressed:
        mouse_clicks += 1

# 初始化键盘和鼠标事件监听
keyboard_listener = keyboard.Listener(on_press=on_key_press)
mouse_listener = mouse.Listener(on_click=on_mouse_click)
keyboard_listener.start()   # 启动监听
mouse_listener.start()

#-----------------------------------------------------------------------------
# 钩子信息
webhook = ""
secret = ""

# 上报信息
reportTime = "21:00" # 播报时间
reportTitle = "今日工作量统计"      #title
reportFormat = "### 今日工作量:\n> mac键盘- {} 次\n\n> mac鼠标- {} 次\n\n🐟🐟又是摸鱼的一天🐟🐟"    #上报格式

script_dir = os.path.dirname(os.path.abspath(__file__))         # 获取当前脚本所在的目录 
jsonFile = os.path.join(script_dir, 'config.json')              # 构建 JSON 文件的完整路径 

print(" JsonFile" + jsonFile)

try:
    with open(jsonFile, 'r', encoding='utf-8') as file:
        data = json.load(file)
    print("JSON 导入成功:", data)
except json.JSONDecodeError as e:
    print(f"JSON 导入失败: {e}")
    sys.exit(1) 
except FileNotFoundError:
    print(f"文件 '{jsonFile}' 未找到")
    sys.exit(1)  
except Exception as e:
    print(f"发生了其他异常: {e}")
    sys.exit(1)  # 退出程序并返回状态码 1

try:
    webhook = data.get('webhook')   # WebHook地址
    secret = data.get('secret')         # 可选：创建机器人勾选“加签”选项时使用
except KeyError as e:
    print(f"Error: {e} 不存在")
    exit(1)  # 退出程序并返回状态码 1

reportTime = data.get('reportTime',reportTime)
reportTitle = data.get('reportTitle',reportTitle)
reportFormat = data.get('reportFormat',reportFormat)


#-----------------------------------------------------------------------------
# 初始化机器人小丁
xiaoding = DingtalkChatbot(webhook, secret=secret)  # 方式二：勾选“加签”选项时使用（v1.5以上新功能）

#-----------------------------------------------------------------------------
# 每天晚上9点执行的任务
def daily_stats():
    global keyboard_clicks, mouse_clicks
    print(f"今天键盘点击次数: {keyboard_clicks}")
    print(f"今天鼠标点击次数: {mouse_clicks}")
    if keyboard_clicks == 0 and mouse_clicks == 0:
        return 
    # Markdown消息@所有人
    xiaoding.send_markdown(title=reportTitle, text=reportFormat.format(keyboard_clicks,mouse_clicks))
    # 重置点击次数
    keyboard_clicks = 0
    mouse_clicks = 0

# 每天晚上9点执行一次统计任务
schedule.every().day.at(reportTime).do(daily_stats)

# 主循环
while True:
    schedule.run_pending()
    time.sleep(1)

# nohup python your_script.py arg1 arg2 > output.log 2>&1 &
